using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Decav.Gatsb.Application;
using Decav.Gatsb.Data;
using System.Net.Mail;
using Decav.Reality;
using Decav.Gatsb;
using System.Text;
using Decav.Security;
using Decav.Gatsb.Configuration;
using Decav.Gatsb.Web;

public partial class CreateAccount : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack && GatsbApplication.Current.UserPresent)
            Response.Redirect("~/Default.aspx");

        ClientScript.RegisterStartupScript(this.GetType(), "SetPrimaryFocus",
            string.Format("document.getElementById(\"{0}\").focus();", nameTextBox.ClientID), true);

        SessionRedirect = Request.QueryString["ReturnUrl"];
    }

    /// <summary>
    /// Gets or sets where this session redirects to after creating a user account.
    /// </summary>
    public string SessionRedirect
    {
        get
        {
            return Session["CreateAccount_Redirect"] as string;
        }
        set
        {
            Session["CreateAccount_Redirect"] = value;
        }
    }
	

    private bool CustomValidate()
    {
        if (!termsOfUseCheck.Checked)
        {
            SetError("Please agree to the terms of use before continuing.");
            return false;
        }

        if (emailTextBox.Text.Trim().Length == 0)
        {
            SetError("Gatsb requires a valid email address to provide you with a login and notifications.");
            return false;
        }

        if (!birthdayBox.IsValid || birthdayBox.Value < DateTime.Today.AddYears(-100))
        {
            SetError("Please enter your birthday in Month/Day/Year (ex: 2/14/1986) format.");
            return false;
        }

        if (passwordTextBox.Text != confirmPasswordTextBox.Text)
        {
            SetError("Your passwords don't match.  Make sure both the password and confirmation password are the same.");
            return false;
        }

        try
        {
            new EmailAddress(emailTextBox.Text);
        }
        catch
        {
            SetError("Gatsb requires a valid email address to provide you with a login and notifications.");
            return false;
        }

        if (passwordTextBox.Text.Trim().Length == 0)
        {
            SetError("Please create a password for yourself.  Your password may be 4-20 characters long, and contain any characters.");
            return false;
        }

        if (new PhoneNumber(phoneNumberTextBox.Text).ToString().Length != 10)
        {
            SetError("Please provide us with your 10 digit mobile phone number.  We will use this number to send you notifications and allow you to send us posts.");
            return false;
        }

        if (postalCodeTextBox.Text.Trim().Length != 5)
        {
            SetError("Please supply us with your postal code so we can find places around your area.");
            return false;
        }

        return true;
    }

    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (!Page.IsValid)
            return;

        if (!CustomValidate())
            return;

        EmailAddress address = new EmailAddress(emailTextBox.Text);
        PhoneNumber telNumber = new PhoneNumber(phoneNumberTextBox.Text);
        TelephoneServiceProvider telProvider = GetTelephoneProvider();

        using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
        {
            if (adapt.CheckUserExists(address))
            {
                SetError("A user with that email address already exists.  If you forgot your password, <a href=\"ResetPassword.aspx\">reset it here</a>.");
                return;
            }

            if (adapt.CheckUserExists(telNumber))
            {
                SetError("A user with that mobile number already exists.  If you forgot your password, <a href=\"ResetPassword.aspx\">reset it here</a>.");
                return;
            }
        }

        Decav.Gatsb.User user = CreateUserObject(address, telNumber, telProvider);

        if (user == null)
            return;

        HashedPassword password = HashedPassword.HashPassword(passwordTextBox.Text);

        GatsbApplication.Current.CreateNewUser(user, password);
        /*
        using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
        {
            UserProfile profile = adapt.GetUserProfile(GatsbApplication.Current.CurrentUser.Id);
            profile.BirthdayDate = birthdayBox.Value;

            adapt.UpdateUserProfile(user, profile);
        }*/

        GatsbWebApplication.Current.NewAccountHasNotSeenHelp = true;
        Response.Redirect("~/ValidatePhone.aspx", true);
    }

    private TelephoneServiceProvider GetTelephoneProvider()
    {
        return TelephoneServiceProvider.GetProvider(phoneProviderDropDown.SelectedType);
    }

    private void SetError(string message)
    {
        serverErrorMsgDiv.InnerHtml = message;
        serverErrorMsgDiv.Visible = true;
    }

    private Decav.Gatsb.User CreateUserObject(EmailAddress address, PhoneNumber telNumber, TelephoneServiceProvider telProvider)
    {
        Decav.Gatsb.User user = Decav.Gatsb.User.CreateNewUser(address, telNumber, telProvider);

        PersonName name = PersonName.Empty;
        if (!PersonName.TryParse(nameTextBox.Text, out name))
        {
            SetError("Please give us your real name, including a first name and last name.  You may use initials for your last name.");
            return null;
        }

        user.PostalCode = postalCodeTextBox.Text.Trim();
        user.Name = name;
        return user;
    }
}
